package org.share.comm.net;

import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * UDP连接客户端，提供向UDP服务器发送数据方法
 * 
 * @author hhm
 *
 */
public class UDPClient {

	private static final Logger logger = LoggerFactory.getLogger(UDPClient.class);

	/**
	 * 向指定UDP服务器发送字符串
	 * 
	 * @param ip
	 * @param port
	 * @param msg
	 */
	public static void sendMessage(String ip, int port, String msg) {
		try {
			byte[] buf = msg.getBytes("utf-8");
			sendMessage(ip, port, buf);
		} catch (UnsupportedEncodingException e) {
			logger.error("string encoding exception.",e);
		}
		
	}

	/**
	 * 向指定UDP服务器发送字节流数据
	 * 
	 * @param ip
	 * @param port
	 * @param msg
	 */
	public static void sendMessage(String ip, int port, byte[] msg) {
		try {
			DatagramSocket server = new DatagramSocket();
			DatagramPacket packet = new DatagramPacket(msg, 0, msg.length, InetAddress.getByName(ip), port);
			server.send(packet);
			server.close();
		} catch (Exception e) {
			logger.error("sendMessage(\"" + ip + "\"," + port + ",\"" + msg + "\")", e);
		}
	}

	public static void main(String[] args) {
		UDPClient.sendMessage("127.0.0.1", 8080, "我是一个小老虎了各位时代感为哦就地方oiler谁的风景过分了谁的风景我房间时代感了");
		UDPClient.sendMessage("127.0.0.1", 8081, "我是一个小老虎了各位时代感为哦就地方oiler谁的风景过分了谁的风景我房间时代感了");
		UDPClient.sendMessage("127.0.0.1", 8081, "我是一个小老虎了各位时代感为哦就地方oiler谁的风景过分了谁的风景我房间时代感了");
	}
}
